<template>
  <div class="app-container">
    <!--查询-->
    <div class="filter-container">

      <el-input v-model="listQuery.productName" placeholder="产品名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <!-- <el-select v-model="listQuery.importance" :placeholder="$t('table.importance')" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select> -->

      <!--查询产品分类-->
      <el-select v-model="listQuery.productTypeId" placeholder="产品分类" class="filter-item" style="width: 130px">
        <el-option label="请选择产品分类" :value="0" />
        <el-option v-for="item in calendarTypeOptions" :key="item.id" :label="item.categoryName" :value="item.id" />
      </el-select>

      <el-select v-model="listQuery.productState" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option label="上架" :value="1" />
        <el-option label="下架" :value="2" />
      </el-select>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }} <!-- 搜索 -->
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('table.add') }} <!-- 添加 -->
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('table.export') }} <!-- 导出 -->
      </el-button>
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        {{ $t('table.reviewer') }} <!-- 审核人 -->
      </el-checkbox>
    </div>

    <!--显示数据-->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >

      <el-table-column :label="$t('table.id')" prop="id" sortable="custom" align="center" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column :label="$t('table.date')" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.publishDate }}</span>
        </template>
      </el-table-column> -->

      <el-table-column label="产品名称" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.productName.substr(0,6) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="产品副名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.productSubtitle.substr(0,6) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="产品分类" align="center">
        <template slot-scope="{row}">
          <span>{{ row.categoryName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="产品原价($)" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.productSalePrice }}</span>
        </template>
      </el-table-column>

      <el-table-column label="销售价格($)" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.productSPromotion }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品详情" align="center">
        <template slot-scope="{row}">
          <span>{{ row.productDetails.substr(0,6) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="产品重量(kg)" align="center">
        <template slot-scope="{row}">
          <span>{{ row.productWeight }}</span>
        </template>
      </el-table-column>

      <el-table-column label="产品是否上架" align="center">
        <template slot-scope="{row}">
          <span style="color:red;">{{ row.productState==1?"上架":"下架" }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('table.edit') }}
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            加入回收站
          </el-button>
          <el-button size="mini" type="danger" @click="sku(row)">
            添加规格
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :page-sizes="[5, 10, 15, 20]"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!--添加/修改-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">

        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="temp.productName" placeholder="产品名称" />
        </el-form-item>

        <el-form-item label="产品副名称" prop="productSubtitle">
          <el-input v-model="temp.productSubtitle" placeholder="产品副名称" />
        </el-form-item>

        <el-form-item label="产品副名称" prop="productSubtitle">
          <!--产品分类-->
          <el-select v-model="temp.productTypeId" :placeholder="$t('table.type')" clearable class="filter-item" style="width: 130px">
            <el-option v-for="item in calendarTypeOptions" :key="item.id" :label="item.categoryName" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="产品原价" prop="productSalePrice">
          <el-input v-model="temp.productSalePrice" placeholder="产品原价(1.00$)" />
        </el-form-item>

        <el-form-item label="产品销售价" prop="productSPromotion">
          <el-input v-model="temp.productSPromotion" placeholder="产品销售价(1.00$)" />
        </el-form-item>

        <el-form-item label="产品重量" prop="productWeight">
          <el-input v-model="temp.productWeight" placeholder="产品重量(1.00kg)" />
        </el-form-item>

        <el-form-item label="产品介绍" prop="productDetails">
          <el-input v-model="temp.productDetails" type="textarea" :rows="2" placeholder="商品详情" />
        </el-form-item>

        <el-form-item label="上传图片">
          <el-upload
            ref="file"
            :file-list="filefileList"
            :action="fileAction"
            :before-upload="fileBeforeUpload"
            :on-success="uploadsuccess"
          >
            <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="产品是否上架" prop="productState">
          <el-radio-group v-model="temp.productState">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <div v-if="dialogPvVisible">
      <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
        <SkuWrap :order="type" />
      </el-dialog>
    </div>

  </div>
</template>

<script>
import { CommodityList, createArticle, deleteArticle, updateArticle, CategoryArticle, UpdateState, CreateImg } from '@/api/Commodity'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import SkuWrap from '@/views/SKU/sku'

const calendarTypeOptions = []

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.id] = cur.categoryName
  return acc
}, {})

export default {
  name: 'ComplexTable',
  // eslint-disable-next-line vue/no-unused-components
  components: { Pagination, SkuWrap },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      type: 0,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 5,
        skipCount: 0,
        maxResultCount: 5,
        importance: undefined,
        title: undefined,
        productName: undefined,
        productTypeId: 0,
        productState: undefined,
        productDisplay: 1,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        productName: '',
        productSubtitle: '',
        productDisplay: 1,
        productSalePrice: '',
        productSPromotion: '',
        productWeight: '',
        productDetails: '',
        productTypeId: '',
        productState: 1
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        // productName: [{ required: true, message: '请输入产品名称', trigger: 'change' }],
        // productSalePrice: [{ required: true, message: '请输入价格', trigger: 'change' }],
        // productWeight: [{ required: true, message: '请输入产品重量', trigger: 'blur' }]
      },
      downloadLoading: false,
      formData: {
        imageURL: [],
        imageCategroy: 1,
        imageSId: ''
      },
      fileAction: 'https://localhost:44341/api/app/special/upload',
      filefileList: []
    }
  },
  watch: {
  },
  created() {
    this.getList()
    this.CategoryChagn()
  },
  methods: {
    sku(rows) {
      this.dialogPvVisible = true
      this.type = rows.id
    },
    getList() {
      this.listLoading = true
      // 计算跳过的条数
      this.listQuery.skipCount = (this.listQuery.page - 1) * this.listQuery.limit
      // 赋值
      this.listQuery.maxResultCount = this.listQuery.limit
      // eslint-disable-next-line no-undef
      CommodityList(this.listQuery).then(response => {
        // console.log(response)
        this.list = response.items
        this.total = response.totalCount

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.1 * 1000)
      })
    },
    sizechange(val) {
      alert(val)
      this.listQuery.maxResultCount = val
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },

    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },

    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },

    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then((x) => {
            console.log(this.temp)
            localStorage.productId = x.id
            this.formData.imageSId = x.id
            this.list.unshift(this.temp)
            // 添加图片
            if (this.formData.imageSId > 0) {
              alert(1)
              console.log(this.formData)
              CreateImg(this.formData)
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.formData.imageSId = this.temp.id
            // 添加图片
            if (this.formData.imageSId > 0) {
              // alert(1)
              console.log(this.formData)
              CreateImg(this.formData)
            }
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    // 删除
    handleDelete(row, index) {
      // eslint-disable-next-line no-trailing-spaces
      UpdateState(row).then((x) => {
        this.$notify({
          title: '成功',
          message: '加入成功',
          type: 'success',
          duration: 2000
        })
      })

      this.list.splice(index, 1)
    },

    handleFetchPv(pv) {
      deleteArticle(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },

    // 产品分类加载
    CategoryChagn() {
      CategoryArticle().then(response => {
        console.log(response)
        this.calendarTypeOptions = response.items
      }
      )
    },

    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },

    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },

    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },

    // 判断上传图片的大小
    fileBeforeUpload(file) {
      const isRightSize = file.size / 1024 / 1024 < 10
      if (!isRightSize) {
        this.$message.error('文件大小超过 10MB')
      }
      return isRightSize
    },

    // 图片上传成功返回值
    uploadsuccess(x, g) {
      console.log(x)
      this.formData.imageURL.push(x)
      console.log(this.formData.imageURL)
    }
  }
}
</script>
